package device

import (
	"encoding/json"
	"errors"
	"time"
)

type Switch struct {
	Command
}

func NewSwitch() *Switch {
	return &Switch{}
}

// 操作开关
func (c *Switch) Act(sta string, act int) error {
	err := c.Parser(nil, act)
	if err != nil {
		return err
	}

	payload, err := json.Marshal(c)
	if err != nil {
		DelSign(c.Done)
		return err
	}

	return c.SendCommand(sta, string(payload), 1, false)
}

// 解析数据
func (c *Switch) Parser(m interface{}, action int) error {
	if action != OPEN && action != CLOSE {
		return errors.New("action value is 0 or 1")
	}

	c.Type = TYPE_SWITCH
	c.Time = time.Now().Unix()
	c.Action = int64(action)
	c.Done = CreateSign() // 创建信号

	return nil
}
